package com.xsy.middleware.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xsy.middleware.controller.SyncCrmTableData;
import com.xsy.middleware.controller.SyncCrmTableFile;
import com.xsy.middleware.service.DataBackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Description: 定时同步数据
 * @Author: 黎炎松
 * @Date: 2024/4/25 17:49
 */
@Slf4j
@Component
public class SyncCrmData {

    @Autowired
    private DataBackService dataBackService;

    @Autowired
    private SyncCrmTableData syncCrmTableData;

    @Autowired
    private SyncCrmTableFile syncCrmTableFile;

    /**
     * 定时任务同步数据  每天凌晨执行
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void syncCrmData() {
        try {
            log.info("定时任务同步数据开始 ==============> ");
            Long startTime = System.currentTimeMillis();

            // 获取已经建表的配置信息
            JSONArray dataBackList = dataBackService.getDataBackupByCreate(1);

            // 进行数据同步
            for (Object obj : dataBackList) {
                JSONObject dataBack = (JSONObject) obj;
                String tableName = dataBack.getString("objectApiKey__c");
                log.info("同步数据、文件 开始:=====> " + tableName);

                // 更新表数据
                syncCrmTableData.syncCrmTableData(tableName);

                // 更新文件
                syncCrmTableFile.syncCrmTableFile(tableName, 1);

                // 使用多线程 会导致 用户访问频率超出限制
                //Thread t = new Thread(() -> {
                //});
                //t.start();

                log.info("同步数据、文件 结束:=====> " + tableName);
            }

            long endTime = (System.currentTimeMillis() - startTime ) / 1000;
            log.info("定时任务同步数据结束 ==============> 耗时: {} m  {} s", (endTime / 60), (endTime % 60));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
